package com.uw.uwconfig.server.controller;


import com.uw.uwconfig.server.cluster.Cluster;
import com.uw.uwconfig.server.mapper.ConfigsMapper;
import com.uw.uwconfig.server.model.Configs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
public class UWConfigController {

    private final ConfigsMapper configsMapper;
    private final Cluster cluster;

    Map<String, Long> VERSIONS = new HashMap<>();


    @GetMapping("/list")
    public List<Configs> list(String app, String env, String namespace) {
        return configsMapper.list(app, env, namespace);
    }

    @PostMapping("/update")
    public List<Configs> update(String app, String env, String namespace, @RequestBody Map<String, String> properties) {
        properties.forEach((k,v) -> {
            saveOrUpdate(new Configs(app, env, namespace, k, v));
        });

        VERSIONS.put(String.format("%s-%s-%s", app, env, namespace), System.currentTimeMillis());
        return configsMapper.list(app, env, namespace);
    }

    private void saveOrUpdate(Configs configs) {
        Configs dbConfig = configsMapper.select(configs.getApp(), configs.getEnv(), configs.getNamespace(), configs.getPkey());
        if (ObjectUtils.isEmpty(dbConfig)) {
            configsMapper.insert(configs);
        } else {
            configsMapper.update(configs);
        }
    }

    @GetMapping("/version")
    public long version(String app, String env, String namespace) {
        return VERSIONS.getOrDefault(String.format("%s-%s-%s", app, env, namespace), -1L);
    }


    @GetMapping("/status")
    public boolean status() {
        return cluster.status();
    }

}
